package org.jeecg.modules.procurement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanPlusUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.procurement.entity.BussMaterialProcurement;
import org.jeecg.modules.procurement.service.IBussMaterialProcurementDetailService;
import org.jeecg.modules.procurement.service.IBussMaterialProcurementService;
import org.jeecg.modules.procurement.vo.BussMaterialProcurementDetailVo;
import org.jeecg.modules.procurement.vo.BussMaterialProcurementPage;
import org.jeecg.modules.procurement.vo.BussMaterialProcurementPageInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 原料采购订单
 * @Author: jeecg-boot
 * @Date:   2024-06-06
 * @Version: V1.0
 */
@Api(tags="原料采购订单")
@RestController
@RequestMapping("/business/bussMaterialProcurement")
@Slf4j
public class BussMaterialProcurementController {
	@Autowired
	private IBussMaterialProcurementService bussMaterialProcurementService;
	@Autowired
	private IBussMaterialProcurementDetailService bussMaterialProcurementDetailService;
	
	/**
	 * 分页列表查询
	 *
	 * @param bussMaterialProcurement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "原料采购订单-分页列表查询")
	@ApiOperation(value="原料采购订单-分页列表查询", notes="原料采购订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BussMaterialProcurementPage>> queryPageList(BussMaterialProcurementPage bussMaterialProcurement,
																@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																HttpServletRequest req) {
		QueryWrapper<BussMaterialProcurementPage> queryWrapper = QueryGenerator.initQueryWrapper(bussMaterialProcurement, req.getParameterMap());
		Page<BussMaterialProcurementPage> page = new Page<BussMaterialProcurementPage>(pageNo, pageSize);
		IPage<BussMaterialProcurementPage> bussMaterialProcurementDetailVoIPage = bussMaterialProcurementService.pagelist(page,queryWrapper);
//		IPage<BussMaterialProcurement> pageList = bussMaterialProcurementService.page(page, queryWrapper);
		return Result.OK(bussMaterialProcurementDetailVoIPage);
	}

	/**
	 * 以明细表为主表
	 * @param bussMaterialProcurement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="原料采购订单-分页列表查询", notes="原料采购订单-分页列表查询")
	@GetMapping(value = "/page/list")
	public Result<IPage<BussMaterialProcurementPage>> pageList(BussMaterialProcurementPage bussMaterialProcurement,
																	@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	HttpServletRequest req) {
		QueryWrapper<BussMaterialProcurementPage> queryWrapper = QueryGenerator.initQueryWrapper(bussMaterialProcurement, req.getParameterMap());
//		queryWrapper.like(bussMaterialProcurement.getExt1()!=null, "ext1",bussMaterialProcurement.getExt1());
		Page<BussMaterialProcurementPage> page = new Page<BussMaterialProcurementPage>(pageNo, pageSize);
		IPage<BussMaterialProcurementPage> bussMaterialProcurementDetailVoIPage = bussMaterialProcurementService.procurementPage(page,queryWrapper);
//		IPage<BussMaterialProcurement> pageList = bussMaterialProcurementService.page(page, queryWrapper);
		return Result.OK(bussMaterialProcurementDetailVoIPage);
	}

	
	/**
	 *   添加
	 *
	 * @param bussMaterialProcurementPage
	 * @return
	 */
	@AutoLog(value = "原料采购订单-添加")
	@ApiOperation(value="原料采购订单-添加", notes="原料采购订单-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_material_procurement:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BussMaterialProcurementPage bussMaterialProcurementPage) {
		BussMaterialProcurement bussMaterialProcurement = new BussMaterialProcurement();
		BeanUtils.copyProperties(bussMaterialProcurementPage, bussMaterialProcurement);
		List<BussMaterialProcurementDetailVo> details = bussMaterialProcurementPage.getDetaillist();

		bussMaterialProcurementService.saveMain(bussMaterialProcurement, details);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param bussMaterialProcurementPage
	 * @return
	 */
	@AutoLog(value = "原料采购订单-编辑")
	@ApiOperation(value="原料采购订单-编辑", notes="原料采购订单-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_material_procurement:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BussMaterialProcurementPage bussMaterialProcurementPage) {
		BussMaterialProcurement bussMaterialProcurement = new BussMaterialProcurement();
		BeanUtils.copyProperties(bussMaterialProcurementPage, bussMaterialProcurement);
		BussMaterialProcurement bussMaterialProcurementEntity = bussMaterialProcurementService.getById(bussMaterialProcurement.getId());
		if(bussMaterialProcurementEntity==null) {
			return Result.error("未找到对应数据");
		}
		List<BussMaterialProcurementDetailVo> details = bussMaterialProcurementPage.getDetaillist();
		bussMaterialProcurementService.updateMain(bussMaterialProcurement, details);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "原料采购订单-通过id删除")
	@ApiOperation(value="原料采购订单-通过id删除", notes="原料采购订单-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_material_procurement:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		bussMaterialProcurementService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "原料采购订单-批量删除")
	@ApiOperation(value="原料采购订单-批量删除", notes="原料采购订单-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_material_procurement:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bussMaterialProcurementService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 根据id查询
	 * @param ids
	 * @return
	 */
	@GetMapping("/queryByIds")
	public Result<List<BussMaterialProcurementPage>> queryByIds(@RequestParam(name="ids",required=true) String ids){
		List<BussMaterialProcurement> bussMaterialProcurements = bussMaterialProcurementService.listByIds(Arrays.asList(ids.split(",")));
		List<BussMaterialProcurementPage> bussMaterialProcurementPages = BeanPlusUtil.toBeanList(bussMaterialProcurements, BussMaterialProcurementPage.class);
		if(!CollectionUtils.isEmpty(bussMaterialProcurementPages)){
			bussMaterialProcurementPages.forEach(item->{
				List<BussMaterialProcurementDetailVo> bussMaterialProcurementDetailVos = bussMaterialProcurementDetailService.selectByMainId(item.getId());
				if(!CollectionUtils.isEmpty(bussMaterialProcurementDetailVos)){
					item.setDetaillist(bussMaterialProcurementDetailVos);
				}
			});
		}
		return Result.OK(bussMaterialProcurementPages);
	}

	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "原料采购订单-通过id查询")
	@ApiOperation(value="原料采购订单-通过id查询", notes="原料采购订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BussMaterialProcurementPage> queryById(@RequestParam(name="id",required=true) String id) {
		BussMaterialProcurement bussMaterialProcurement = bussMaterialProcurementService.getById(id);
		if(bussMaterialProcurement==null) {
			return Result.error("未找到对应数据");
		}
		BussMaterialProcurementPage bussMaterialProcurementPage = BeanPlusUtil.toBean(bussMaterialProcurement, BussMaterialProcurementPage.class);
		List<BussMaterialProcurementDetailVo> bussMaterialProcurementDetailVos = bussMaterialProcurementDetailService.selectByMainId(bussMaterialProcurement.getId());
		if(!CollectionUtils.isEmpty(bussMaterialProcurementDetailVos)){
			bussMaterialProcurementPage.setDetaillist(bussMaterialProcurementDetailVos);
		}
		return Result.OK(bussMaterialProcurementPage);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "原料采购订单明细通过主表ID查询")
	@ApiOperation(value="原料采购订单明细主表ID查询", notes="原料采购订单明细-通主表ID查询")
	@GetMapping(value = "/queryBussMaterialProcurementDetailByMainId")
	public Result<List<BussMaterialProcurementDetailVo>> queryBussMaterialProcurementDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussMaterialProcurementDetailVo> bussMaterialProcurementDetailList = bussMaterialProcurementDetailService.selectByMainId(id);
		return Result.OK(bussMaterialProcurementDetailList);
	}

	/**
	 * 计算数量
	 * @param vo
	 * @return
	 */
	@PostMapping("/compute/quantity")
	public Result<?> computeQuantity(@RequestBody BussMaterialProcurementDetailVo vo){
		BussMaterialProcurementDetailVo bussMaterialProcurementDetailVo = bussMaterialProcurementDetailService.computeQuantity(vo);
		return Result.OK(bussMaterialProcurementDetailVo);
	}


	/**
	 * 到货信息
	 * @param bussMaterialProcurement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping("/arrayInfo")
	public Result<?> arrayInfo(BussMaterialProcurementPageInfo bussMaterialProcurement,
							   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							   HttpServletRequest req){
		QueryWrapper<BussMaterialProcurementPageInfo> queryWrapper = QueryGenerator.initQueryWrapper(bussMaterialProcurement, req.getParameterMap());
		queryWrapper.isNotNull("warehouse_date");
		Page<BussMaterialProcurementPageInfo> page = new Page<BussMaterialProcurementPageInfo>(pageNo, pageSize);
		IPage<BussMaterialProcurementPageInfo> bussMaterialProcurementDetailVoIPage = bussMaterialProcurementService.arrayInfo(page,queryWrapper);
		return Result.OK(bussMaterialProcurementDetailVoIPage);
	}



	/**
    * 导出excel
    *
    * @param request
    * @param bussMaterialProcurement
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_material_procurement:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BussMaterialProcurement bussMaterialProcurement) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<BussMaterialProcurement> queryWrapper = QueryGenerator.initQueryWrapper(bussMaterialProcurement, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
          List<String> selectionList = Arrays.asList(selections.split(","));
          queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<BussMaterialProcurement> bussMaterialProcurementList = bussMaterialProcurementService.list(queryWrapper);

      // Step.3 组装pageList
      List<BussMaterialProcurementPage> pageList = new ArrayList<BussMaterialProcurementPage>();
      for (BussMaterialProcurement main : bussMaterialProcurementList) {
          BussMaterialProcurementPage vo = new BussMaterialProcurementPage();
          BeanUtils.copyProperties(main, vo);
          List<BussMaterialProcurementDetailVo> bussMaterialProcurementDetailList = bussMaterialProcurementDetailService.selectByMainId(main.getId());

		  vo.setDetaillist(bussMaterialProcurementDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "原料采购订单列表");
      mv.addObject(NormalExcelConstants.CLASS, BussMaterialProcurementPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("原料采购订单数据", "导出人:"+sysUser.getRealname(), "原料采购订单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_material_procurement:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BussMaterialProcurementPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BussMaterialProcurementPage.class, params);
              for (BussMaterialProcurementPage page : list) {
                  BussMaterialProcurement po = new BussMaterialProcurement();
                  BeanUtils.copyProperties(page, po);
				  List<BussMaterialProcurementDetailVo> details = page.getDetaillist();
//				  bussMaterialProcurementService.saveMain(po, BeanPlusUtil.toBeanList(details,BussMaterialProcurementDetail.class));
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
